package com.example.pt.controller;


import com.example.pt.dto.ApiResponse;
import com.example.pt.entity.Post;
import com.example.pt.entity.User;
import com.example.pt.repository.PostRepository;
import com.example.pt.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/posts")
public class PostController {

    @Autowired
    private PostRepository postRepository;
    @Autowired
    private UserRepository userRepository;

    // 帖子列表
    @GetMapping("/postList")
    public ApiResponse postList() {
        List<Post> posts = postRepository.findAll();
        return ApiResponse.success(posts);
    }

    // 当前帖子
    @PostMapping("/getCurrentPost")
    public ApiResponse getCurrentPost(@RequestBody Post post){
        Long post_id = post.getPost_id();
        Post post1 = postRepository.findById(post_id).get();
        return ApiResponse.success(post1);
    }

    // 发帖
    @PostMapping("/createPost")
    public ApiResponse createPost(@RequestBody Post post) {
        // 根据 user_id 查询用户名
        if (post.getUser_id() != null) {
            Optional<User> userOpt = userRepository.findById(post.getUser_id().longValue());
            userOpt.ifPresent(user -> post.setUsername(user.getUsername()));
        }
        postRepository.save(post);
        return ApiResponse.success(post);
    }

    // 删除
    @PostMapping("/delete")
    public ApiResponse delete(@RequestBody Post post){
        postRepository.deleteById(post.getPost_id());
        return ApiResponse.success("删除成功");
    }
}


